﻿Option Strict On
Option Explicit On

Imports System.Web
Imports System.Text
Imports System.Text.RegularExpressions

Public Class URLRewrite
    Implements IHttpModule

    Private qs As New StringBuilder
    Private myPathParam As String()
    Public Sub Dispose() Implements Web.IHttpModule.Dispose

    End Sub

    Public Sub Init(context As Web.HttpApplication) Implements Web.IHttpModule.Init
        AddHandler context.BeginRequest, AddressOf OnBeginRequest
    End Sub
    Private Sub OnBeginRequest(ByVal sender As Object, ByVal e As EventArgs)

        Dim app As HttpApplication = CType(sender, HttpApplication)
        Dim requestpath As String = app.Request.Path
        Dim rpLower As String = requestpath.ToLower

        qs.Append(app.Request.ServerVariables("QUERY_STRING").Trim)
        Dim ext As String = "^.+\.((svc)|(jpg)|(gif)|(js)|(css)|(less)|(ashx)|(png)|(txt)|(jpeg)|(ico)|(pdf)|(browser)|(bmp)|(xml)|(swf)|(xls)|(xlsx)|(doc)|(docx)|(woff)|(woff2)|(svg)|(axd)|(ttf)|(eot)|(webm)|(mp4)|(ogg))$"
        If Regex.IsMatch(rpLower, ext, RegexOptions.Multiline) Then
            Exit Sub
        End If

        If rpLower.Contains("norewrite") OrElse Not app.Request.QueryString.Item("norewrite") Is Nothing Then
            Exit Sub
        End If

        ext = "^.+\.((html))$"
        If Regex.IsMatch(rpLower, ext, RegexOptions.Multiline) Then
            If rpLower.Contains("404error") Then
                app.Response.StatusCode = 404
            Else
                Exit Sub
            End If
        End If

        Dim path = requestpath
        Dim splitter As Char() = {"/"c}
        myPathParam = path.Split(splitter, StringSplitOptions.RemoveEmptyEntries)

        If myPathParam.Length = 0 Then
            DoPropertySite(app)
        ElseIf myPathParam(0).Contains("dashboard") Then
            DoAdminDashboard(app)
        End If

    End Sub

    Private Sub DoPropertySite(ByVal app As HttpApplication)
        Dim path As String = "/"
        Dim page As String = "Site.aspx"

        path = String.Format("{0}{1}", path, page)
        app.Context.RewritePath(path, "", qs.ToString)
    End Sub

    Private Sub DoAdminDashboard(ByVal app As HttpApplication)
        If myPathParam.Length = 0 Then
            Exit Sub
        ElseIf myPathParam.Length = 2 Then
            qs.AppendFormat("&ContentClass={0}", myPathParam(1).Replace("aspx", ""))
        End If

        app.Context.RewritePath("~/Admin.aspx", "", qs.ToString)
    End Sub
End Class
